package com.meiyuetao.myt.sale.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import com.jd.open.api.sdk.domain.order.ItemInfo;
import com.jd.open.api.sdk.domain.order.OrderSearchInfo;
import com.meiyuetao.myt.core.constant.VoucherTypeEnum;
import com.meiyuetao.myt.customer.dao.CustomerAccountHistDao;
import com.meiyuetao.myt.customer.dao.CustomerProfileDao;
import com.meiyuetao.myt.customer.entity.CustomerAccountHist;
import com.meiyuetao.myt.customer.entity.CustomerAccountHist.CustomerAccountHistAccountTypeEnum;
import com.meiyuetao.myt.customer.entity.CustomerAccountHist.CustomerAccountHistOccurTypeEnum;
import com.meiyuetao.myt.customer.entity.CustomerCoinsHistory;
import com.meiyuetao.myt.customer.entity.CustomerProfile;
import com.meiyuetao.myt.customer.entity.CustomerProfile.CustomerLevelEnum;
import com.meiyuetao.myt.customer.entity.CustomerProfile.RewardModeEnum;
import com.meiyuetao.myt.customer.service.CustomerAccountHistService;
import com.meiyuetao.myt.customer.service.CustomerCoinsHistoryService;
import com.meiyuetao.myt.customer.service.CustomerProfileService;
import com.meiyuetao.myt.finance.entity.PayNotifyHistory;
import com.meiyuetao.myt.finance.service.PayNotifyHistoryService;
import com.meiyuetao.myt.job.BusinessNotifyService;
import com.meiyuetao.myt.kuajing.entity.KjOrderInfo;
import com.meiyuetao.myt.kuajing.entity.KjPaymentInfo;
import com.meiyuetao.myt.kuajing.entity.KjSkuStatusCodeEnum;
import com.meiyuetao.myt.kuajing.entity.KjUserValidateInfo;
import com.meiyuetao.myt.kuajing.service.KjOrderInfoService;
import com.meiyuetao.myt.kuajing.service.KjPaymentInfoService;
import com.meiyuetao.myt.kuajing.service.KjUserValidateInfoService;
import com.meiyuetao.myt.md.dao.*;
import com.meiyuetao.myt.md.entity.*;
import com.meiyuetao.myt.md.entity.BindCommodity.ComeFromEnum;
import com.meiyuetao.myt.md.entity.GiftPaper.GiftPaperStatusEnum;
import com.meiyuetao.myt.md.entity.MoneyPaper.PaperStatusEnum;
import com.meiyuetao.myt.md.service.BoxService;
import com.meiyuetao.myt.md.service.CommodityService;
import com.meiyuetao.myt.md.service.KuajingMessageService;
import com.meiyuetao.myt.partner.dao.PurchaseCodeDao;
import com.meiyuetao.myt.sale.dao.*;
import com.meiyuetao.myt.sale.entity.*;
import com.meiyuetao.myt.sale.entity.BoxOrder.*;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail.BoxOrderDetailStatusEnum;
import com.meiyuetao.myt.stock.entity.CommodityStock;
import com.meiyuetao.myt.stock.entity.StockInOut;
import com.meiyuetao.myt.stock.entity.StorageLocation;
import com.meiyuetao.myt.stock.service.CommodityStockService;
import com.meiyuetao.myt.stock.service.StockInOutService;
import com.meiyuetao.myt.vip.dao.VipBakMoneyHistoryDao;
import com.meiyuetao.myt.vip.dao.VipCustomerLevelHistoryDao;
import com.meiyuetao.myt.vip.dao.VipLevelDao;
import com.meiyuetao.myt.vip.dao.VipScoreHistoryDao;
import com.meiyuetao.myt.vip.entity.*;
import com.meiyuetao.myt.vip.entity.VipBakMoneyHistory.VipBakMoneyHistoryStatusEnum;
import com.meiyuetao.myt.vip.entity.VipScoreHistory.VipScoreHistoryStatusEnum;
import com.meiyuetao.myt.vip.service.VipBakMoneyHistoryService;
import com.meiyuetao.myt.vip.service.VipCustomerProfileService;
import com.meiyuetao.myt.vip.service.VipScoreHistoryService;
import com.meiyuetao.util.SignTool;
import com.taobao.api.domain.Order;
import com.taobao.api.domain.Trade;
import lab.s2jh.auth.dao.UserR2RoleDao;
import lab.s2jh.auth.entity.Role;
import lab.s2jh.auth.entity.User;
import lab.s2jh.auth.entity.UserR2Role;
import lab.s2jh.auth.service.RoleService;
import lab.s2jh.auth.service.UserService;
import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.audit.envers.ExtRevisionListener;
import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;
import lab.s2jh.core.web.json.HibernateAwareObjectMapper;
import lab.s2jh.ctx.DynamicConfigService;
import lab.s2jh.ctx.FreemarkerService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class BoxOrderService extends BaseService<BoxOrder, Long> {
    private static Logger logger = LoggerFactory.getLogger(BoxOrderService.class);
    @Autowired
    KjUserValidateInfoService kjUserValidateInfoService;
    @Autowired
    private BoxService boxService;
    @Autowired
    private CustomerProfileService customerProfileService;
    @Autowired
    private CustomerProfileDao customerProfileDao;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private BoxOrderDetailService boxOrderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private KuajingMessageService kuajingMessageService;
    @Autowired
    private KjPaymentInfoService kjPaymentInfoService;
    @Autowired
    private KjOrderInfoService kjOrderInfoService;
    @Autowired
    private BoxOrderDetailCommodityService boxOrderDetailCommodityService;
    @Autowired
    private BusinessNotifyService businessNotifyService;
    @Autowired
    private DynamicConfigService dynamicConfigService;
    @Autowired
    private FreemarkerService freemarkerService;
    @Autowired
    private VipScoreHistoryService vipScoreHistoryService;
    @Autowired
    private VipBakMoneyHistoryService vipBakMoneyHistoryService;
    @Autowired
    private VipCustomerProfileService vipCustomerProfileService;
    @Autowired
    private CustomerAccountHistService customerAccountHistService;
    @Autowired
    private CustomerCoinsHistoryService customerCoinsHistoryService;
    @Autowired
    private PayNotifyHistoryService payNotifyHistoryService;

    @Autowired
    private BoxOrderDao boxOrderDao;
    @Autowired
    private BoxOrderDetailDao boxOrderDetailDao;
    @Autowired
    private CommodityDao commodityDao;
    @Autowired
    private MoneyPaperDao moneyPaperDao;
    @Autowired
    private MoneyPaperHistoryDao moneyPaperHistoryDao;
    @Autowired
    private PersonalMessageDao personalMessageDao;
    @Autowired
    private PersonalMessageItemDao personalMessageItemDao;
    @Autowired
    private GiftPaperDao giftPaperDao;
    @Autowired
    private UserR2RoleDao userR2RoleDao;
    @Autowired
    private BindCommodityDao bindCommodityDao;
    @Autowired
    private StockInOutService stockInOutService;
    @Autowired
    private CommodityStockService commodityStockService;
    @Autowired
    private BoxOrderInDeLogDao boxOrderInDeLogDao;
    @Autowired
    private BoxOrderDetailCommodityDao boxOrderDetailCommodityDao;
    @Autowired
    private VipScoreHistoryDao vipScoreHistoryDao;
    @Autowired
    private CustomerAccountHistDao customerAccountHistDao;
    @Autowired
    private PurchaseCodeDao purchaseCodeDao;
    @Autowired
    private VipBakMoneyHistoryDao vipBakMoneyHistoryDao;
    @Autowired
    private VipLevelDao vipLevelDao;
    @Autowired
    private VipCustomerLevelHistoryDao vipCustomerLevelHistoryDao;
    @Autowired
    private OrderTracingDao orderTracingDao;
    @Value("${ylcf.partnerid}")
    private String ylcfPartnerid;
    @Value("${ylcf.refund.url}")
    private String refundUrl;
    @Value("${ylcf.key}")
    private String ylcfKey;

    @Override
    protected BaseDao<BoxOrder, Long> getEntityDao() {
        return boxOrderDao;
    }

    // 订单完结
    public void successClose(BoxOrder entity) {
        // 追加操作记录
        entity.addOperationEvent("订单完结", AuthContextHolder.getAuthUserPin());
        // 已处理过直接返回
        if (entity.getActualSuccessTime() != null) {
            return;
        }
        // 更新当前订单客户对应的有效订单数
        CustomerProfile orderCustomerProfile = customerProfileDao.findOne(entity.getCustomerProfile().getId());
        if (orderCustomerProfile.getValidOrderCount() == null) {
            orderCustomerProfile.setValidOrderCount(1);
        } else {
            orderCustomerProfile.setValidOrderCount(orderCustomerProfile.getValidOrderCount() + 1);
        }
        if (orderCustomerProfile.getCustomerLevel() == null || CustomerLevelEnum.NORMAL.equals(orderCustomerProfile.getCustomerLevel())) {
            if (BoxOrderModeEnum.SUBSCRIBE.equals(entity.getOrderMode())) {
                orderCustomerProfile.setCustomerLevel(CustomerLevelEnum.SVIP);
            } else {
                orderCustomerProfile.setCustomerLevel(CustomerLevelEnum.VIP);
            }
        } else if (CustomerLevelEnum.VIP.equals(orderCustomerProfile.getCustomerLevel())) {
            if (BoxOrderModeEnum.SUBSCRIBE.equals(entity.getOrderMode())) {
                orderCustomerProfile.setCustomerLevel(CustomerLevelEnum.SVIP);
            }
        }
        Date now = new Date();
        entity.setOrderStatus(BoxOrderStatusEnum.S70CLS);
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
        for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
            if (!BoxOrderDetailStatusEnum.S70CLS.equals(boxOrderDetail.getOrderDetailStatus())) {
                boxOrderDetail.setOrderDetailStatus(BoxOrderDetailStatusEnum.S70CLS);
                boxOrderDetail.addOperationEvent("行项完结", AuthContextHolder.getAuthUserPin());
                boxOrderDetailDao.save(boxOrderDetail);
            }
        }
        entity.setActualSuccessTime(now);
        entity.setActualSuccessOperator(AuthContextHolder.getAuthUserPin());
        entity = this.save(entity);
        // http://oa.rpset.net:3000/issues/2004
        // 更新用户值，主要用于用户的等级判断，正常情况下等同于spent_money
        if (orderCustomerProfile.getCustomerValue() == null) {
            orderCustomerProfile.setCustomerValue(entity.getActualAmount());
        } else {
            orderCustomerProfile.setCustomerValue(orderCustomerProfile.getCustomerValue().add(entity.getActualAmount()));
        }
        if (orderCustomerProfile.getId() == 301) {
            System.out.println(orderCustomerProfile.getId() + "," + entity.getId());
        }
        orderCustomerProfile = customerProfileDao.save(orderCustomerProfile);
        // 冻结积分转积分
        List<VipCustomerProfile> vipCustomerProfiles = freezeScoreToScore(entity);
        // 重新绑定关系
        for (VipCustomerProfile item : vipCustomerProfiles) {
            VipLevel oVipLevel = item.getVipLevel();
            VipCustomerProfile upstream1 = item.getUpstream();
            while (upstream1 != null && !"MYT".equals(upstream1.getVipLevel().getCode()) && !"XE".equals(upstream1.getVipLevel().getCode())
                    && oVipLevel.getLevelIndex() <= upstream1.getVipLevel().getLevelIndex()) {
                upstream1 = upstream1.getUpstream();
            }
            if (item.getUpstream() != null && !item.getUpstream().equals(upstream1)) {
                item.setUpstream(upstream1);
                vipCustomerProfileService.save(item);
            }
        }
        // 计算返利
        calBackMoney(entity);
    }

    /**
     * 计算返利
     *
     * @param entity
     * @author harvey
     * @since 2015/11/06
     */
    private void calBackMoney(BoxOrder entity) {
        GroupPropertyFilter groupPropertyFilter;
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<VipBakMoneyHistory> vipBakMoneyHistories = vipBakMoneyHistoryService.findByFilters(groupPropertyFilter);
        for (VipBakMoneyHistory vipBakMoneyHistory : vipBakMoneyHistories) {
            if (VipBakMoneyHistoryStatusEnum.LOCK.equals(vipBakMoneyHistory.getStatus()) || VipBakMoneyHistoryStatusEnum.FREEZE.equals(vipBakMoneyHistory.getStatus())) {
                CustomerProfile customerProfile = vipBakMoneyHistory.getCustomerProfile();
                VipCustomerProfile vipCustomerProfile = customerProfile.getVipCustomerProfile();
                vipCustomerProfile.setBackMoney(vipCustomerProfile.getBackMoney().add(vipBakMoneyHistory.getBackMoney()));
                vipCustomerProfile = vipCustomerProfileService.save(vipCustomerProfile);
                vipBakMoneyHistory.setStatus(VipBakMoneyHistoryStatusEnum.ADDED);
                vipBakMoneyHistoryDao.save(vipBakMoneyHistory);
            }
        }
    }

    /**
     * 冻结积分转积分
     *
     * @param entity
     * @author harvey
     * @since 2015/11/06
     */
    private List<VipCustomerProfile> freezeScoreToScore(BoxOrder entity) {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<VipScoreHistory> vipScoreHistorys = vipScoreHistoryService.findByFilters(groupPropertyFilter);
        List<VipCustomerProfile> vipCustomerProfiles = new ArrayList<VipCustomerProfile>();
        for (VipScoreHistory vipScoreHistory : vipScoreHistorys) {
            if (VipScoreHistoryStatusEnum.LOCK.equals(vipScoreHistory.getStatus()) || VipScoreHistoryStatusEnum.FREEZE.equals(vipScoreHistory.getStatus())) {
                CustomerProfile customerProfile = vipScoreHistory.getCustomerProfile();
                BigDecimal levelUpScore = vipScoreHistory.getScore();
                VipCustomerProfile vipCustomerProfile = customerProfile.getVipCustomerProfile();
                String memo = "之前等级：" + vipCustomerProfile.getVipLevel().getName() + ",积分：" + vipCustomerProfile.getScore() + ";";
                vipCustomerProfile.setScore(vipCustomerProfile.getScore().add(levelUpScore));
                vipCustomerProfile = vipCustomerProfileService.save(vipCustomerProfile);
                vipScoreHistory.setStatus(VipScoreHistoryStatusEnum.ADDED);
                vipScoreHistoryDao.save(vipScoreHistory);
                // 升级
                List<VipLevel> vipLevels = vipLevelDao.findAllCached();
                VipLevel vipLevel = null;
                BigDecimal cScore = vipCustomerProfile.getScore();
                int levelIndex = vipCustomerProfile.getVipLevel().getLevelIndex();
                BigDecimal temp = BigDecimal.ZERO;
                for (VipLevel item : vipLevels) {
                    if (!"MYT".equals(item.getCode()) && !"XE".equals(item.getCode()) && levelIndex >= item.getLevelIndex() && item.getScore().compareTo(temp) >= 0
                            && item.getScore().compareTo(cScore) <= 0) {
                        temp = item.getScore();
                        vipLevel = item;
                    }
                }
                if (vipLevel != null && !vipLevel.equals(vipCustomerProfile.getVipLevel())) {
                    vipCustomerProfile.setVipLevel(vipLevel);
                    vipCustomerProfile.setVipLevelName(vipLevel.getName());
                    vipCustomerProfile = vipCustomerProfileService.save(vipCustomerProfile);
                    // 升级的用户放入集合中
                    vipCustomerProfiles.add(vipCustomerProfile);
                    // 写入历史记录
                    VipCustomerLevelHistory vipCustomerLevelHistory = new VipCustomerLevelHistory();
                    vipCustomerLevelHistory.setCustomerProfile(customerProfile);
                    vipCustomerLevelHistory.setLevelUpScore(levelUpScore);
                    memo = memo + "升级后等级：" + vipLevel.getName() + ",积分：" + vipCustomerProfile.getScore();
                    vipCustomerLevelHistory.setMemo(memo);
                    vipCustomerLevelHistory.setBoxOrder(entity);
                    vipCustomerLevelHistoryDao.save(vipCustomerLevelHistory);
                }
            }
        }
        return vipCustomerProfiles;
    }

    // 取消订单
    public void cancelOrder(BoxOrder entity) {
        // 记录审计原状态
        ExtRevisionListener.setOldState(entity.getOrderStatus().name());
        // 设置新状态
        entity.setOrderStatus(BoxOrderStatusEnum.S90CANCLE);
        entity.addOperationEvent("订单取消", AuthContextHolder.getAuthUserPin());
        // 审计记录新状态
        ExtRevisionListener.setNewState(entity.getOrderStatus().name());
        // 审计记录操作动作
        ExtRevisionListener.setOperationEvent(BoxOrderOperationEventEnum.CANCLE.name());
        // 取消订单退回礼品券、优惠券
        backMoneyPaper(entity);
        backGiftPaper(entity);
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
        // 对于未付款确认的订单,退回可售库存
        for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
            BoxOrderDetailStatusEnum orderDetailStatus = boxOrderDetail.getOrderDetailStatus();
            if (BoxOrderDetailStatusEnum.S10O.equals(orderDetailStatus) || BoxOrderDetailStatusEnum.S25PYD.equals(orderDetailStatus)
                    || BoxOrderDetailStatusEnum.S15O.equals(orderDetailStatus) || BoxOrderDetailStatusEnum.S30C.equals(orderDetailStatus)
                    || BoxOrderDetailStatusEnum.S35C.equals(orderDetailStatus) || BoxOrderDetailStatusEnum.S20PYD.equals(orderDetailStatus)) {
                groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrderDetail", boxOrderDetail));
                List<BoxOrderDetailCommodity> boxOrderDetailCommodities = boxOrderDetailCommodityService.findByFilters(groupPropertyFilter);
                for (BoxOrderDetailCommodity boxOrderDetailCommodity : boxOrderDetailCommodities) {
                    Commodity commodity = boxOrderDetailCommodity.getCommodity();
                    BigDecimal canSaleCount = commodity.getCanSaleCount();
                    if (canSaleCount == null) {
                        commodity.setCanSaleCount(boxOrderDetailCommodity.getQuantity());
                    } else {
                        commodity.setCanSaleCount(canSaleCount.add(boxOrderDetailCommodity.getQuantity()));
                    }
                    // add 2015/5/12 需求 #6586 取消订单加上判断
                    CharSequence cs = "闪购/单品订单";
                    if (entity.getAdminMemo() != null && entity.getAdminMemo().contains(cs)) {
                        Integer dailyUserCanBuy = commodity.getDailyUserCanBuy();
                        if (dailyUserCanBuy == null) {
                            commodity.setDailyUserCanBuy(boxOrderDetailCommodity.getQuantity().intValue());
                        } else {
                            commodity.setDailyUserCanBuy(dailyUserCanBuy + boxOrderDetailCommodity.getQuantity().intValue());
                        }
                    }
                    commodityDao.save(commodity);
                }
            }
        }
        // 销售订单取消退回锁定库存量
        for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
            groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrderDetail", boxOrderDetail));
            List<BoxOrderDetailCommodity> boxOrderDetailCommodities = boxOrderDetailCommodityService.findByFilters(groupPropertyFilter);
            for (BoxOrderDetailCommodity bodc : boxOrderDetailCommodities) {
                if (bodc.getStorageLocation() != null && bodc.getSalingLockedQuantity() != null && BigDecimal.ZERO.compareTo(bodc.getSalingLockedQuantity()) < 0) {
                    Commodity commodity = bodc.getCommodity();
                    StorageLocation storageLocation = bodc.getStorageLocation();
                    CommodityStock commodityStock = commodityStockService.findBy(commodity, storageLocation);
                    Validation.isTrue(commodityStock != null, "商品：" + commodity.getDisplay() + ",库存地：" + storageLocation.getDisplay() + "  不存在");
                    StockInOut stockInOut = new StockInOut(entity.getOrderSeq() + "." + boxOrderDetail.getSn(), String.valueOf(bodc.getId()), VoucherTypeEnum.XSD, commodityStock);
                    stockInOut.setDiffSalingQuantity(bodc.getSalingLockedQuantity().negate());
                    stockInOut.setOperationSummary("销售订单取消退回锁定库存量");
                    stockInOutService.saveCascade(stockInOut);
                    commodity.setTotalFreezedStockCount(commodity.getTotalFreezedStockCount().subtract(bodc.getQuantity()));
                    commodityDao.save(commodity);
                }
            }
        }
        entity = boxOrderDao.save(entity);
        for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
            boxOrderDetail.addOperationEvent("行项取消", AuthContextHolder.getAuthUserPin());
            boxOrderDetail.setOrderDetailStatus(BoxOrderDetailStatusEnum.S90CANCLE);
            boxOrderDetailDao.save(boxOrderDetail);
        }
        // 冻结积分转取消
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<VipScoreHistory> vipScoreHistorys = vipScoreHistoryService.findByFilters(groupPropertyFilter);
        for (VipScoreHistory vipScoreHistory : vipScoreHistorys) {
            if (VipScoreHistoryStatusEnum.LOCK.equals(vipScoreHistory.getStatus()) || VipScoreHistoryStatusEnum.FREEZE.equals(vipScoreHistory.getStatus())) {
                vipScoreHistory.setStatus(VipScoreHistoryStatusEnum.CANCEL);
                vipScoreHistoryDao.save(vipScoreHistory);
            }
        }
        // 冻结返利转取消
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<VipBakMoneyHistory> vipBakMoneyHistories = vipBakMoneyHistoryService.findByFilters(groupPropertyFilter);
        for (VipBakMoneyHistory vipBakMoneyHistory : vipBakMoneyHistories) {
            if (VipBakMoneyHistoryStatusEnum.LOCK.equals(vipBakMoneyHistory.getStatus()) || VipBakMoneyHistoryStatusEnum.FREEZE.equals(vipBakMoneyHistory.getStatus())) {
                vipBakMoneyHistory.setStatus(VipBakMoneyHistoryStatusEnum.CANCEL);
                vipBakMoneyHistoryDao.save(vipBakMoneyHistory);
            }
        }
        // 2016.04.01 追加，取消订单将 客户的 余额 和 积分（金币） 返还
        backCoins(entity, groupPropertyFilter);
        backAccount(entity, groupPropertyFilter);
        // 异步发送通知
        // businessNotifyService.sendOrderCancelNotifyEmailAsync(entity);
    }

    private void backGiftPaper(BoxOrder entity) {
        List<GiftPaper> giftPapers = giftPaperDao.findByOrderSeq(entity.getOrderSeq());
        if (giftPapers != null && giftPapers.size() > 0) {
            for (GiftPaper giftPaper : giftPapers) {
                if (giftPaper.getExpireTime() != null && giftPaper.getExpireTime().before(new Date())) {
                    giftPaper.setPaperStatus(GiftPaperStatusEnum.S40EPR);
                } else {
                    giftPaper.setPaperStatus(GiftPaperStatusEnum.S20ACT);
                }
                giftPaperDao.save(giftPaper);
            }
        }
    }

    //取消订单返还余额
    private void backAccount(BoxOrder entity, GroupPropertyFilter groupPropertyFilter) {
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<CustomerAccountHist> customerAccountHists = customerAccountHistService.findByFilters(groupPropertyFilter);
        for (CustomerAccountHist customerAccountHist : customerAccountHists) {
            if (CustomerAccountHistOccurTypeEnum.CONS.equals(customerAccountHist.getOccurType())) {
                CustomerProfile customerProfile = customerAccountHist.getCustomerProfile();
                // 变更前
                BigDecimal before = customerProfile.getCurrentAccount();
                // 变更后
                BigDecimal after = customerProfile.getCurrentAccount().subtract(customerAccountHist.getAmount());
                // 变更
                BigDecimal back = customerAccountHist.getAmount();
                CustomerAccountHist backCah = new CustomerAccountHist();
                backCah.setAccountType(CustomerAccountHistAccountTypeEnum.CURRENT);
                backCah.setAmount(back);
                backCah.setBoxOrder(entity);
                backCah.setCustomerProfile(customerProfile);
                backCah.setBoxOrderDetail(customerAccountHist.getBoxOrderDetail());
                backCah.setMobileNo(customerAccountHist.getMobileNo());
                backCah.setOccurTime(new Date());
                backCah.setOccurType(CustomerAccountHistOccurTypeEnum.REIMB);
                backCah.setSysMemo("后台取消订单返还余额");
                customerAccountHistService.save(backCah);
                customerProfile.setCurrentAccount(after);
                customerProfileService.save(customerProfile);
            }
        }
    }

    // 取消订单返还积分（金币）
    private void backCoins(BoxOrder entity, GroupPropertyFilter groupPropertyFilter) {
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "order", entity));
        List<CustomerCoinsHistory> customerCoinsHistories = customerCoinsHistoryService.findByFilters(groupPropertyFilter);
        for (CustomerCoinsHistory customerCoinsHistory : customerCoinsHistories) {
            if (CustomerCoinsHistory.OperationTypeEnum.PAY.equals(customerCoinsHistory.getOperationType())
                    || CustomerCoinsHistory.OperationTypeEnum.BACKCOINS.equals(customerCoinsHistory.getOperationType())) {
                CustomerProfile customerProfile = customerCoinsHistory.getCustomerProfile();
                // 变更前
                BigDecimal before = customerProfile.getCoins();
                // 变更
                BigDecimal back = customerCoinsHistory.getCoins();
                // 变更后的基本积分
                BigDecimal after = before.subtract(back);
                // 变更后的消费积分
                BigDecimal afterConsumedScore = customerProfile.getConsumedNewScore().subtract(customerCoinsHistory.getBaseNewScore()).subtract(customerCoinsHistory.getGivenNewScore());
                // 消费 增长积分返还
                BigDecimal backGivenScore = customerCoinsHistory.getGivenNewScore();
                CustomerCoinsHistory backCch = new CustomerCoinsHistory();
                backCch.setCoins(BigDecimal.ZERO.subtract(back));
                backCch.setBaseNewScore(BigDecimal.ZERO.subtract(back));
                backCch.setCoinsAfter(after);
                backCch.setCoinsBefore(before);
                backCch.setCustomerProfile(customerProfile);
                backCch.setOrder(entity);
                backCch.setMemo("后台取消订单返还积分");
                backCch.setOperationType(CustomerCoinsHistory.OperationTypeEnum.CANCLECOINS);
                customerCoinsHistoryService.save(backCch);
                customerProfile.setCoins(after);
                customerProfile.setConsumedNewScore(afterConsumedScore);
                customerProfileService.save(customerProfile);
            }
        }
    }

    // 订单提成(冻结金额)处理
    public void orderCustomerAccountHist(BoxOrder boxOrder, BoxOrderDetail boxOrderDetail, BigDecimal payAmount) {
        CustomerProfile intermediaryCustomerProfile = boxOrder.getIntermediaryCustomerProfile();
        if (intermediaryCustomerProfile == null) {
            return;
        }
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "intermediaryCustomerProfile", intermediaryCustomerProfile));
        List<CustomerProfile> intermediaryCustomerProfileList = customerProfileService.findByFilters(groupPropertyFilter);
        Integer recommendCount = intermediaryCustomerProfileList.size();
        if (recommendCount == null) {
            recommendCount = 0;
        }
        if (boxOrderDetail == null) {
            boxOrderDetail = boxOrder.getBoxOrderDetails().get(0);
        }
        BigDecimal rewardRate = null;
        BigDecimal rewardAmount = new BigDecimal(0);
        // 哎呦盒子订单，按照原有的‘订单佣金比例计算’，美月淘订单，改成‘商品佣金计算’
        if (boxOrderDetail.getBox().getBarcode().equals("00000000")) {
            for (BoxOrderDetailCommodity bodc : boxOrderDetail.getBoxOrderDetailCommodities()) {
                if (!Boolean.TRUE.equals(bodc.getGift())) {
                    Commodity commodity = bodc.getCommodity();
                    if (commodity.getRewardRate() != null && commodity.getRewardRate().compareTo(new BigDecimal(0)) > 0) {
                        rewardAmount = rewardAmount.add(commodity.getRewardRate().multiply(bodc.getFinalPrice()).multiply(bodc.getQuantity()));
                    } else {
                        Category category = commodity.getCategory();
                        if (category != null && category.getRewardRate() != null && category.getRewardRate().compareTo(new BigDecimal(0)) > 0) {
                            rewardAmount = rewardAmount.add(category.getRewardRate().multiply(bodc.getFinalPrice()).multiply(bodc.getQuantity()));
                        }
                    }
                }
            }
        } else {
            if (recommendCount <= 10 && recommendCount > 0) {
                rewardRate = new BigDecimal("0.02");
            } else if (recommendCount <= 30) {
                rewardRate = new BigDecimal("0.03");
            } else if (recommendCount <= 60) {
                rewardRate = new BigDecimal("0.05");
            } else if (recommendCount <= 100) {
                rewardRate = new BigDecimal("0.07");
            } else {
                rewardRate = new BigDecimal("0.1");
            }
            BigDecimal customerRewardRate = intermediaryCustomerProfile.getRewardRate();
            if (customerRewardRate != null) {
                RewardModeEnum rewardModeEnum = intermediaryCustomerProfile.getRewardMode();
                if (RewardModeEnum.FIX.equals(rewardModeEnum)) {
                    rewardRate = customerRewardRate;
                } else if (RewardModeEnum.MAX.equals(rewardModeEnum)) {
                    rewardRate = rewardRate.compareTo(customerRewardRate) > 0 ? rewardRate : customerRewardRate;
                } else if (RewardModeEnum.MIN.equals(rewardModeEnum)) {
                    rewardRate = rewardRate.compareTo(customerRewardRate) < 0 ? rewardRate : customerRewardRate;
                }
            }
            rewardAmount = payAmount.multiply(rewardRate);
        }
        // 追加推荐人的账户收支记录
        if (rewardAmount.compareTo(new BigDecimal(0)) == 1) {
            CustomerAccountHist customerAccountHist = new CustomerAccountHist();
            customerAccountHist.setCustomerProfile(intermediaryCustomerProfile);
            customerAccountHist.setAmount(rewardAmount);
            customerAccountHist.setOccurType(CustomerAccountHistOccurTypeEnum.DED);
            customerAccountHist.setOccurTime(new Date());
            customerAccountHist.setBoxOrder(boxOrder);
            customerAccountHist.setBoxOrderDetail(boxOrderDetail);
            customerAccountHist.setAccountType(CustomerAccountHistAccountTypeEnum.FROZEN);
            customerAccountHist.setSysMemo(boxOrderDetail.getBoxOrder().getOrderFrom() + "订单" + boxOrder.getOrderSeq() + "的提成冻结金额，提成额：" + rewardAmount);
            customerAccountHistDao.save(customerAccountHist);
            intermediaryCustomerProfile.setFrozenAccount(rewardAmount.add(intermediaryCustomerProfile.getFrozenAccount()));
            customerProfileService.save(intermediaryCustomerProfile);
        }
    }

    @MetaData("订单调价")
    public BoxOrder modifyPrice(BoxOrder entity) {
        BoxOrder dbEntity = boxOrderDao.findOne(entity.getId());
        if (!dbEntity.getActualAmount().equals(entity.getActualAmount())) {
            BigDecimal diff = entity.getActualAmount().subtract(dbEntity.getActualAmount());
            BigDecimal orderActualAmount = entity.getActualAmount();
            if (entity.getOrderStatus().equals(BoxOrderStatusEnum.S10O) || entity.getOrderStatus().equals(BoxOrderStatusEnum.S15O)) {
                BigDecimal orderOriginalAmount = entity.getOriginalAmount();
                BigDecimal perActualAmount = orderActualAmount.divide(orderOriginalAmount, 5, BigDecimal.ROUND_HALF_EVEN);
                BigDecimal tempDetailActualAmount = BigDecimal.ZERO;
                List<BoxOrderDetail> boxOrderDetails = entity.getBoxOrderDetails();
                for (int i = 0; i < boxOrderDetails.size(); i++) {
                    BoxOrderDetail bod = boxOrderDetails.get(i);
                    BigDecimal iActualAmount;
                    if (i != boxOrderDetails.size() - 1) {
                        iActualAmount = perActualAmount.multiply(bod.getOriginalAmount());
                        tempDetailActualAmount = tempDetailActualAmount.add(iActualAmount);
                    } else {
                        iActualAmount = orderActualAmount.subtract(tempDetailActualAmount);
                    }
                    bod.setActualAmount(iActualAmount);
                    bod.setPrice(bod.getActualAmount());
                    bod.setDiscountAmount(bod.getOriginalAmount().subtract(iActualAmount));
                    GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                    groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrderDetail", bod));
                    List<BoxOrderDetailCommodity> boxOrderDetailCommodities = boxOrderDetailCommodityService.findByFilters(groupPropertyFilter);
                    BigDecimal perDetailActualAmount = iActualAmount.divide(bod.getOriginalAmount(), 5, BigDecimal.ROUND_HALF_EVEN);
                    BigDecimal tempDetailCommodityActualAmount = BigDecimal.ZERO;
                    for (int j = 0; j < boxOrderDetailCommodities.size(); j++) {
                        BoxOrderDetailCommodity bodc = boxOrderDetailCommodities.get(j);
                        BigDecimal jActualAmount = BigDecimal.ZERO;
                        if (j != boxOrderDetailCommodities.size() - 1) {
                            jActualAmount = perDetailActualAmount.multiply(bodc.getOriginalAmount());
                            tempDetailCommodityActualAmount = tempDetailCommodityActualAmount.add(jActualAmount);
                        } else {
                            jActualAmount = iActualAmount.subtract(tempDetailCommodityActualAmount);
                        }
                        bodc.setActualAmount(jActualAmount);
                        bodc.setDiscountAmount(bodc.getOriginalAmount().subtract(jActualAmount));
                    }
                }
                // TODO: 写入订单条件记录数据
                BoxOrderInDeLog boid = new BoxOrderInDeLog();
                boid.setBoxOrder(entity);
                boid.setInDeAmount(diff);
                boid.setReason("订单调价--原始金额：" + entity.getOriginalAmount() + ",实付金额:" + entity.getActualAmount() + ",原初始金额：" + dbEntity.getOriginalAmount() + ",实付金额："
                        + dbEntity.getActualAmount() + ")");
                boid.setOccurTime(new Date());
                boid.setMoneyOperator(AuthContextHolder.getAuthUserPin());
                boxOrderInDeLogDao.save(boid);
            } else {
                throw new RuntimeException("订单状态为“用户已下单”或“计划进行中”才允许订单改价");
            }
        }
        return super.save(entity);
    }

    @MetaData("确认收货")
    public void recvConfirm(BoxOrder entity) {
        // 计算订单预期完结时间
        String days = dynamicConfigService.getString("cfg.order.success.days", "30");
        Calendar successDate = Calendar.getInstance();
        successDate.add(Calendar.DAY_OF_YEAR, Integer.valueOf(days));
        entity.setOrderStatus(BoxOrderStatusEnum.S60R);
        entity.setActualConfirmTime(new Date());
        entity.setActualConfirmOperator(AuthContextHolder.getAuthUserPin());
        entity.setAutoSuccessTime(successDate.getTime());
        if (entity.getCustomerProfile().getReadyCommentCount() != null) {
            entity.getCustomerProfile().setReadyCommentCount(entity.getCustomerProfile().getReadyCommentCount() + 1);
        } else {
            entity.getCustomerProfile().setReadyCommentCount(1);
        }
        // 追加操作记录
        entity.addOperationEvent("订单确认收货", AuthContextHolder.getAuthUserPin());
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
        for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
            if (!BoxOrderDetailStatusEnum.S60R.equals(boxOrderDetail.getOrderDetailStatus()) && !BoxOrderDetailStatusEnum.S70CLS.equals(boxOrderDetail.getOrderDetailStatus())) {
                boxOrderDetail.setOrderDetailStatus(BoxOrderDetailStatusEnum.S60R);
                boxOrderDetail.addOperationEvent("行项收货完成", AuthContextHolder.getAuthUserPin());
                boxOrderDetailDao.save(boxOrderDetail);
            }
        }
        this.save(entity);
    }

    /**
     * 订单发货
     *
     * @param entity
     */
    public void deliverySave(BoxOrder entity) {
        // 追加操作记录
        entity.addOperationEvent("订单发货", AuthContextHolder.getAuthUserPin());
        for (BoxOrderDetail boxOrderDetail : entity.getBoxOrderDetails()) {
            boxOrderDetail.setLogisticsNo("申通");
            boxOrderDetail.setLogisticsName("11223344");
            // 简化发货状态处理，一次完成发货
            boxOrderDetail.setOrderDetailStatus(BoxOrderDetailStatusEnum.S50DF);
            boxOrderDetail.setDeliveryFinishTime(new Date());
            boxOrderDetailDao.save(boxOrderDetail);
            // BoxOrder boxOrder = boxOrderDetail.getBoxOrder();
            // 订单追踪表，发货的时候添加通知
            OrderTracing orderTracing = new OrderTracing();
            orderTracing.setBoxOrder(entity);
            orderTracing.setOrderDetailSid(boxOrderDetail.getId());
            orderTracing.setOccurTime(new Date());
            orderTracing.setTracingText("您的当期订单已发货");
            orderTracing.setCustomerProfile(entity.getCustomerProfile());
            orderTracingDao.save(orderTracing);
        }
        entity.setOrderStatus(BoxOrderStatusEnum.S50DF);
        entity.setDeliveryFinishTime(new Date());
        boxOrderDao.save(entity);
        // 发货设置积分冻结
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<VipScoreHistory> vipScoreHistorys = vipScoreHistoryService.findByFilters(groupPropertyFilter);
        for (VipScoreHistory vipScoreHistory : vipScoreHistorys) {
            if (VipScoreHistoryStatusEnum.LOCK.equals(vipScoreHistory.getStatus())) {
                vipScoreHistory.setStatus(VipScoreHistoryStatusEnum.FREEZE);
                vipScoreHistoryDao.save(vipScoreHistory);
            }
        }
    }

    /**
     * 免单
     *
     * @param entity
     * @author harvey
     * @since 2015/4/21
     */
    public void free(BoxOrder entity) {
        // 追加操作记录
        boxOrderDao.save(entity);
    }

    /**
     * 取消免单
     *
     * @param entity
     * @author harvey
     * @since 2015/4/21
     */
    public void freeCancle(BoxOrder entity) {
        // 追加操作记录
        entity.addOperationEvent("取消免单", AuthContextHolder.getAuthUserPin());
        boxOrderDao.save(entity);

    }

    @MetaData("通知一路财富退款")
    public void sendToYlcf(BoxOrder boxOrder) {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "paySeq", boxOrder.getOrderGroupSeq()));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "payMode", "YLCF"));
        List<PayNotifyHistory> lst = payNotifyHistoryService.findByFilters(groupPropertyFilter);
        if (CollectionUtils.isNotEmpty(lst)) {
            for (PayNotifyHistory payNotifyHistory : lst) {
                if (payNotifyHistory != null) {
                    // 当用户使用一路财富进行结算时，退款流程如下：
                    String custuid = payNotifyHistory.getCustomerProfile().getId().toString();
                    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                    //渠道编号
                    formparams.add(new BasicNameValuePair("partnerid", ylcfPartnerid));
                    //流水号
                    formparams.add(new BasicNameValuePair("custReqSerialno", DateUtil.formatDate(new Date())));
                    // 渠道服务器时间
                    formparams.add(new BasicNameValuePair("localtime", DateUtil.formatDate(new Date())));
                    //渠道用户唯一id
                    formparams.add(new BasicNameValuePair("custuid", custuid));
                    //渠道订单编号
                    formparams.add(new BasicNameValuePair("custorderno", payNotifyHistory.getTradeNo()));
                    //交易密码
                    formparams.add(new BasicNameValuePair("aesTranPwd", ""));
                    //类型 0：后端（不验证交易密码）
                    formparams.add(new BasicNameValuePair("type", "0"));
                    //签名
                    Map<String, String> paramsMap = new HashMap<String, String>();
                    for (NameValuePair nvp : formparams) {
                        paramsMap.put(nvp.getName(), nvp.getValue());
                    }
                    String singStr = SignTool.getSignStr(ylcfKey, paramsMap);
                    formparams.add(new BasicNameValuePair("sign", singStr));
                    // 设置Post数据
                    try {
                        CloseableHttpClient client = HttpClients.createDefault();
                        HttpPost httpPost = new HttpPost(refundUrl);
                        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
                        httpPost.setEntity(entity);
                        HttpResponse httpResponse = client.execute(httpPost);
                        int status = httpResponse.getStatusLine().getStatusCode();
                        if (HttpStatus.SC_OK == status) {
                            boxOrder.setMemo("一路财富退款成功！");
                        } else {
                            boxOrder.setMemo("一路财富退款失败！");
                        }
                        client.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @MetaData("订单退款")
    public void backCommodity(BoxOrder entity) {
        sendToYlcf(entity);
        // 记录审计原状态
        ExtRevisionListener.setOldState(entity.getOrderStatus().name());
        // 设置新状态
        entity.setOrderStatus(BoxOrderStatusEnum.S90CANCLE);
        entity.addOperationEvent("订单退款", AuthContextHolder.getAuthUserPin());

        // 审计记录新状态
        ExtRevisionListener.setNewState(entity.getOrderStatus().name());
        // 审计记录操作动作
        ExtRevisionListener.setOperationEvent(BoxOrderOperationEventEnum.CANCLE.name());
        // 取消订单退回礼品券、优惠券
        backMoneyPaper(entity);
        backGiftPaper(entity);
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        // 2016.04.11 追加，订单退款将 客户的 余额 和 积分（金币） 返还
        backCoins(entity, groupPropertyFilter);
        backAccount(entity, groupPropertyFilter);

        List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
        // 对于退款的订单,不用退回可售库存
        // 销售订单退款 不用退回锁定库存量
        entity = boxOrderDao.save(entity);
        for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
            boxOrderDetail.addOperationEvent("行项取消", AuthContextHolder.getAuthUserPin());
            boxOrderDetail.setOrderDetailStatus(BoxOrderDetailStatusEnum.S90CANCLE);
            boxOrderDetailDao.save(boxOrderDetail);
        }
        // 退还积分
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<VipScoreHistory> vipScoreHistorys = vipScoreHistoryService.findByFilters(groupPropertyFilter);
        List<VipCustomerProfile> vipCustomerProfiles = new ArrayList<VipCustomerProfile>();
        for (VipScoreHistory vipScoreHistory : vipScoreHistorys) {
            CustomerProfile customerProfile = vipScoreHistory.getCustomerProfile();
            BigDecimal levelDownScore = vipScoreHistory.getScore();
            VipCustomerProfile vipCustomerProfile = customerProfile.getVipCustomerProfile();
            String memo = "之前等级：" + vipCustomerProfile.getVipLevel().getName() + ",积分：" + vipCustomerProfile.getScore() + ";";
            vipCustomerProfile.setScore(vipCustomerProfile.getScore().subtract(levelDownScore));
            vipCustomerProfile = vipCustomerProfileService.save(vipCustomerProfile);
            vipScoreHistory.setStatus(VipScoreHistoryStatusEnum.CANCEL);
            vipScoreHistoryDao.save(vipScoreHistory);

            // 降级
            List<VipLevel> vipLevels = vipLevelDao.findAllCached();
            VipLevel vipLevel = null;
            BigDecimal cScore = vipCustomerProfile.getScore();
            int levelIndex = vipCustomerProfile.getVipLevel().getLevelIndex();
            BigDecimal temp = BigDecimal.ZERO;
            for (VipLevel item : vipLevels) {
                if (!"MYT".equals(item.getCode()) && !"XE".equals(item.getCode()) && levelIndex >= item.getLevelIndex() && item.getScore().compareTo(temp) >= 0
                        && item.getScore().compareTo(cScore) <= 0) {
                    temp = item.getScore();
                    vipLevel = item;
                }
            }
            if (vipLevel != null && !vipLevel.equals(vipCustomerProfile.getVipLevel())) {
                vipCustomerProfile.setVipLevel(vipLevel);
                vipCustomerProfile.setVipLevelName(vipLevel.getName());
                vipCustomerProfile = vipCustomerProfileService.save(vipCustomerProfile);
                // 升级的用户放入集合中
                vipCustomerProfiles.add(vipCustomerProfile);
                // 写入历史记录
                VipCustomerLevelHistory vipCustomerLevelHistory = new VipCustomerLevelHistory();
                vipCustomerLevelHistory.setCustomerProfile(customerProfile);
                vipCustomerLevelHistory.setLevelUpScore(levelDownScore);
                memo = memo + "降级后等级：" + vipLevel.getName() + ",积分：" + vipCustomerProfile.getScore();
                vipCustomerLevelHistory.setMemo(memo);
                vipCustomerLevelHistory.setBoxOrder(entity);
                vipCustomerLevelHistoryDao.save(vipCustomerLevelHistory);
            }
        }
        // 退还返利
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "boxOrder", entity));
        List<VipBakMoneyHistory> vipBakMoneyHistories = vipBakMoneyHistoryService.findByFilters(groupPropertyFilter);
        for (VipBakMoneyHistory vipBakMoneyHistory : vipBakMoneyHistories) {
            CustomerProfile customerProfile = vipBakMoneyHistory.getCustomerProfile();
            VipCustomerProfile vipCustomerProfile = customerProfile.getVipCustomerProfile();
            vipCustomerProfile.setBackMoney(vipCustomerProfile.getBackMoney().subtract(vipBakMoneyHistory.getBackMoney()));
            vipCustomerProfile = vipCustomerProfileService.save(vipCustomerProfile);
            vipBakMoneyHistory.setStatus(VipBakMoneyHistoryStatusEnum.CANCEL);
            vipBakMoneyHistoryDao.save(vipBakMoneyHistory);
        }
    }

    private void backMoneyPaper(BoxOrder entity) {
        List<MoneyPaperHistory> moneyPaperHistories = moneyPaperHistoryDao.findByBoxOrder(entity);
        if (moneyPaperHistories != null && moneyPaperHistories.size() > 0) {
            for (MoneyPaperHistory moneyPaperHistory : moneyPaperHistories) {
                MoneyPaper moneyPaper = moneyPaperHistory.getMoneyPaper();
                if (moneyPaper.getPaperStatus() != PaperStatusEnum.S40EPR && moneyPaper.getPaperStatus() != PaperStatusEnum.S50DIS) {
                    moneyPaper.getRestAmount().add(moneyPaperHistory.getAmount());
                    moneyPaperDao.save(moneyPaper);
                }
            }
        }
    }

    @Override
    public BoxOrder save(BoxOrder entity) {
        if (entity.isNotNew()) {
            BoxOrder oldEntity = boxOrderDao.findOne(entity.getId());
            if (oldEntity.getOrderStatus().equals(entity.getOrderStatus())) {
                businessNotifyService.cpsSendAsync(entity);
            }
        }
        return super.save(entity);
    }

    @MetaData("通过订单号查询订单")
    public BoxOrder findByOrderSeq(String tid) {
        return boxOrderDao.findByOrderSeq(tid);
    }

    /**
     * 将Tmall订单列表导入MYT数据库
     *
     * @param tradeList 拉取的订单列表
     * @param map       订单状态对应关系MAP
     * @return
     */
    public String importOrderFromTmall(List<Trade> tradeList, Map<String, BoxOrderStatusEnum> map) {
        String result = "";
        Set<String> notExistcommodityTitls = Sets.newHashSet();
        Box box = boxService.findByProperty("barcode", "00000000");
        for (Trade trade : tradeList) {
            try {
                String orderId = trade.getTid().toString();// 订单号
                BoxOrder boxOrder = boxOrderDao.findByOrderSeq(orderId);
                BoxOrderDetail boxOrderDetail = null;
                if (boxOrder == null) {
                    boxOrder = new BoxOrder();// 订单不存在则新建
                    boxOrderDetail = new BoxOrderDetail(); // 销售订单行项
                } else {
                    List<BoxOrderDetail> boxOrderDetailList = boxOrder.getBoxOrderDetails();
                    if (boxOrderDetailList != null && boxOrderDetailList.size() > 0) {
                        boxOrderDetail = boxOrderDetailList.get(0);
                    }
                }
                BigDecimal detailPrice = BigDecimal.ZERO;
                Boolean allExist = true;
                /**
                 * 遍历订单，一笔交易（Trade）可能包含多笔子订单（Order），这就是一个购物车中的多个商品
                 */
                for (Order order : trade.getOrders()) {
                    String skuId = order.getSkuId();// 商品Sku
                    if (skuId == null)
                        skuId = order.getNumIid().toString();
                    BoxOrderDetailCommodity orderDetailCommodity = null; // 销售订单行项下商品
                    for (BoxOrderDetailCommodity boxOrderDetailCommodity : boxOrderDetail.getBoxOrderDetailCommodities()) {
                        if (skuId.equals(boxOrderDetailCommodity.getCommodity().getTmallSku())) {
                            orderDetailCommodity = boxOrderDetailCommodity;
                        }
                    }
                    if (orderDetailCommodity == null)
                        orderDetailCommodity = new BoxOrderDetailCommodity();
                    // 原价金额
                    orderDetailCommodity.setPrice(new BigDecimal(order.getPrice()));
                    // 原始金额=商品单价*购买数量
                    orderDetailCommodity.setOriginalAmount(new BigDecimal(order.getPrice()).multiply(new BigDecimal(order.getNum())));
                    // 调价后的价格
                    orderDetailCommodity.setModifiedPrice(new BigDecimal(order.getPrice()));
                    detailPrice.add(new BigDecimal(order.getPrice()));
                    // 购买数量
                    orderDetailCommodity.setQuantity(new BigDecimal(order.getNum()));
                    // 总计金额
                    orderDetailCommodity.setActualAmount(new BigDecimal(order.getTotalFee()));
                    // 优惠金额
                    orderDetailCommodity.setDiscountAmount(new BigDecimal(order.getDiscountFee()));
                    Commodity commodity = null;
                    try {
                        commodity = commodityService.findByProperty("tmallSku", skuId);
                    } catch (IllegalArgumentException e) {
                        return "有重复的商品TmallSku:" + skuId;
                    }
                    if (commodity == null) {
                        // 未在MYT匹配到天猫商品
                        notExistcommodityTitls.add(skuId + " | " + order.getTitle());
                        allExist = false;
                        break;
                    } else {
                        orderDetailCommodity.setCommodity(commodity);
                        orderDetailCommodity.setBoxOrder(boxOrder);
                        orderDetailCommodity.setBoxOrderDetail(boxOrderDetail);
                        orderDetailCommodity.setBox(box);
                        boxOrderDetail.getBoxOrderDetailCommodities().add(orderDetailCommodity);
                    }
                }
                if (allExist) {// 所有商品都匹配到才保存订单
                    boxOrder.setOrderSeq(orderId);
                    boxOrder.setOrderFrom(OrderFromEnum.TMALL);
                    // 京东payType（1货到付款, 2邮局汇款, 3自提, 4在线支付, 5公司转账, 6银行转账 ）
                    // String payMode = osi.getPayType();// 支付方式
                    // if (payMode.startsWith("1")) {
                    // boxOrder.setPayMode("OTHR");
                    // } else {
                    // boxOrder.setPayMode("CHINA_BANK");
                    // }
                    boxOrder.setOriginalAmount(new BigDecimal(trade.getTotalFee()));// 原价金额
                    boxOrder.setActualAmount(new BigDecimal(trade.getPayment()));// 实际付款金额
                    boxOrder.setActualPayedAmount(new BigDecimal(trade.getReceivedPayment()));// 已付总金额
                    boxOrder.setDiscountAmount(new BigDecimal(trade.getDiscountFee()));// 折扣金额discount_fee
                    boxOrder.setPostage(new BigDecimal(trade.getPostFee()));// 邮费
                    boxOrder.setSplitPayMode(BoxOrderSplitPayModeEnum.NO);// 分期类型
                    BoxOrderStatusEnum mapOrderState = map.get(trade.getStatus());
                    boxOrder.setOrderStatus(mapOrderState);// 订单状态
                    if (trade.getPayTime() != null) {
                        boxOrder.setPayConfirmTime(trade.getPayTime());
                        boxOrder.setConfirmTime(trade.getPayTime());
                    }
                    if (trade.getCreated() != null) {
                        boxOrder.setOrderTime(trade.getCreated());
                    }
                    CustomerProfile tmallCustomer = customerProfileService.findFirstByProperty("nickName", "天猫客户");
                    if (tmallCustomer == null) {
                        tmallCustomer = new CustomerProfile();
                        tmallCustomer.setNickName("天猫客户");
                        tmallCustomer.setTrueName("天猫客户");
                        customerProfileService.save(tmallCustomer);
                    }
                    boxOrderDetail.setCustomerProfile(tmallCustomer);
                    boxOrderDetail.setBox(box);
                    boxOrderDetail.setSn("100");
                    boxOrderDetail.setOrderDetailStatus(BoxOrderDetailStatusEnum.valueOf(mapOrderState.name()));// 订单状态
                    boxOrderDetail.setPrice(detailPrice); // 价格
                    // boxOrderDetail.setOriginalAmount(new
                    // BigDecimal(trade.getTotalFee()));// 原始价格
                    // boxOrderDetail.setActualAmount(new
                    // BigDecimal(trade.getPayment())); // 已付金额
                    DateTime now = new DateTime();
                    DateTime dt2 = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 0, 0);
                    boxOrderDetail.setReserveDeliveryTime(dt2.toDate());
                    String boxOrderTitle = "";
                    if (trade.getOrders() != null) {
                        Integer itemSize = trade.getOrders().size();
                        if (itemSize == 1) {
                            boxOrderTitle = trade.getOrders().get(0).getTitle();
                        } else if (trade.getOrders().size() > 1) {
                            boxOrderTitle = trade.getOrders().get(0).getSkuPropertiesName() + "等,共" + itemSize + "件商品";
                        }
                        boxOrderDetail.setQuantity(itemSize);
                    }
                    boxOrder.setPostCode(trade.getReceiverZip());// 邮编
                    if (boxOrder.isNew()) {
                        // 新建状态才填写收货信息，防止模糊数据覆盖之前导入的完整数据
                        boxOrder.setReceivePerson(trade.getReceiverName());// 收货人
                        boxOrder.setMobilePhone(trade.getReceiverMobile());// 电话号
                        boxOrder.setDeliveryAddr(trade.getReceiverAddress());// 收货地址
                    }
                    boxOrder.setDeliveryCity(trade.getReceiverCity());// 收货城市
                    // boxOrder.setDeliveryProvince(trade.gR);// 收货省
                    boxOrder.setCustomerMemo(trade.getBuyerMessage());// 客户备注
                    boxOrder.setMemo(trade.getTradeMemo());// 备注
                    ObjectMapper objectMapper = HibernateAwareObjectMapper.getInstance();
                    String rawDateString;
                    try {
                        rawDateString = objectMapper.writeValueAsString(trade);
                        boxOrder.setRawData(rawDateString);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                    boxOrder.setTitle(boxOrderTitle);
                    boxOrder.setCustomerProfile(tmallCustomer);
                    boxOrder.setRawData(trade.toString());
                    boxOrderDetail.setBoxOrder(boxOrder);
                    boxOrder.getBoxOrderDetails().add(boxOrderDetail);
                    result += "导入Tmall订单：" + boxOrder.getOrderSeq() + ";";
                    // 发票信息
                    boxOrder.setInvoiceType(trade.getInvoiceType());// 发票类型
                    boxOrder.setInvoiceTitle(trade.getInvoiceName());// 发票标题
                    boxOrder.setInvoiceContent(trade.getInvoiceName()); // 发票内容
                    boxOrder.setInvoiceCompany("北京美月淘电子商务有限公司");
                    boxOrderDao.save(boxOrder);
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }
        // 未在MYT匹配到的天猫商品 发送提醒 ,放在最后一次性发送
        if (CollectionUtils.isNotEmpty(notExistcommodityTitls)) {
            PersonalMessage personalMessage = new PersonalMessage();
            String message = "";
            for (String msg : notExistcommodityTitls) {
                message += msg + ";<br> ";
            }
            result += "未找到天猫商品： " + message + " 请在系统中维护商品的‘天猫sku’或添加新商品";
            personalMessage.setContents("未找到天猫商品：<br>  " + message + " 请在系统中维护商品的‘天猫sku’或添加新商品");
            User user = userService.findByProperty("signinid", "admin");
            personalMessage.setPublishUser(user);
            personalMessage.setPublishTime(new Date());
            personalMessage.setTitle("天猫订单导入后台，未找到相关商品");
            personalMessageDao.save(personalMessage);
            Role role = roleService.findByProperty("code", "ROLE_OP_MGR");// 运维主管（接收所有提醒）
            if (role != null) {
                personalMessageDao.save(personalMessage);
                List<UserR2Role> userR2Roles = userR2RoleDao.findByRole_Id(role.getId());
                for (UserR2Role item : userR2Roles) {
                    PersonalMessageItem personalMessageItem = new PersonalMessageItem();
                    personalMessageItem.setPersonalMessage(personalMessage);
                    personalMessageItem.setTargetUser(item.getUser());
                    personalMessageItemDao.save(personalMessageItem);
                }
            }
        }
        return result;
    }

    // 从京东导入订单
    public String importOrderFromJd(List<OrderSearchInfo> osis, Map<String, BoxOrderStatusEnum> map) {
        String result = "";
        Set<String> commodityTitls = Sets.newHashSet();
        Box box = boxService.findByProperty("barcode", "00000000");
        for (OrderSearchInfo osi : osis) {
            try {
                String orderId = osi.getOrderId();
                BoxOrder boxOrder = boxOrderDao.findByOrderSeq(orderId);
                String orderState = osi.getOrderState();
                BoxOrderStatusEnum mapOrderState = map.get(orderState);
                if (boxOrder != null) {
                    /*
                     * if (!mapOrderState.equals(boxOrder.getOrderStatus())) {
                     * result += "更新订单和行项状态：" + boxOrder.getOrderSeq() + "的状态" +
                     * boxOrder.getOrderStatus() + "→" + map.get(orderState) +
                     * ";"; boxOrder.setOrderStatus(map.get(orderState)); for
                     * (BoxOrderDetail bod : boxOrder.getBoxOrderDetails()) {
                     * bod
                     * .setOrderDetailStatus(BoxOrderDetailStatusEnum.valueOf(
                     * mapOrderState.name())); }
                     * 
                     * boxOrderDao.save(boxOrder); }
                     */
                } else {
                    boxOrder = new BoxOrder();
                    BoxOrderDetail boxOrderDetail = new BoxOrderDetail();
                    BigDecimal detailPrice = BigDecimal.ZERO;
                    Boolean allExist = true;
                    for (ItemInfo itemInfo : osi.getItemInfoList()) {
                        BoxOrderDetailCommodity bodc = new BoxOrderDetailCommodity();
                        bodc.setPrice(new BigDecimal(itemInfo.getJdPrice()));
                        bodc.setModifiedPrice(new BigDecimal(itemInfo.getJdPrice()));
                        detailPrice.add(new BigDecimal(itemInfo.getJdPrice()));
                        bodc.setQuantity(new BigDecimal(itemInfo.getItemTotal()));
                        String skuId = itemInfo.getSkuId();
                        String skuName = itemInfo.getSkuName();
                        Commodity commodity = commodityService.findByProperty("jdSku", skuId);
                        if (commodity == null) {
                            commodity = commodityService.findByProperty("title", skuName);
                            BindCommodity bindCommodity = new BindCommodity();
                            bindCommodity.setComeFrom(ComeFromEnum.JD);
                            bindCommodity.setName(skuName);
                            bindCommodity.setSku(skuId);
                            if (commodity == null) {
                                commodityTitls.add("(订单号:" + orderId + ")" + skuName);
                                bindCommodity.setMemo("订单号:" + orderId);
                                allExist = false;
                                break;
                            } else {
                                commodity.setJdSku(skuId);
                                commodityService.save(commodity);
                                bindCommodity.setMemo("名称相同");
                                bindCommodity.setCommodity(commodity);
                            }
                            bindCommodityDao.save(bindCommodity);
                        }
                        if (commodity != null) {
                            bodc.setCommodity(commodity);
                            bodc.setBoxOrder(boxOrder);
                            bodc.setBoxOrderDetail(boxOrderDetail);
                            bodc.setBox(box);
                            boxOrderDetail.getBoxOrderDetailCommodities().add(bodc);
                        }
                    }
                    if (allExist) {
                        boxOrder.setOrderSeq(orderId);
                        boxOrder.setOrderFrom(OrderFromEnum.JD);
                        // 京东payType（1货到付款, 2邮局汇款, 3自提, 4在线支付, 5公司转账, 6银行转账 ）
                        String payMode = osi.getPayType();
                        if (payMode.startsWith("1")) {
                            boxOrder.setPayMode("OTHR");
                        } else {
                            boxOrder.setPayMode("CHINA_BANK");
                        }
                        boxOrder.setOriginalAmount(new BigDecimal(osi.getOrderPayment()));
                        boxOrder.setActualAmount(new BigDecimal(osi.getOrderPayment()));
                        boxOrder.setActualPayedAmount(new BigDecimal(osi.getOrderPayment()));
                        boxOrder.setPostage(new BigDecimal(osi.getFreightPrice()));
                        boxOrder.setSplitPayMode(BoxOrderSplitPayModeEnum.NO);
                        boxOrder.setOrderStatus(mapOrderState);
                        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        try {
                            if (osi.getPaymentConfirmTime() != null) {
                                boxOrder.setPayConfirmTime(dt.parse(osi.getPaymentConfirmTime()));
                                boxOrder.setConfirmTime(dt.parse(osi.getPaymentConfirmTime()));
                            }
                            if (osi.getOrderStartTime() != null) {
                                boxOrder.setOrderTime(dt.parse(osi.getOrderStartTime()));
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        CustomerProfile jdCustomer = customerProfileService.findFirstByProperty("nickName", "京东客户");
                        if (jdCustomer == null) {
                            jdCustomer = new CustomerProfile();
                            jdCustomer.setNickName("京东客户");
                            jdCustomer.setTrueName("京东客户");
                            customerProfileService.save(jdCustomer);
                        }
                        boxOrderDetail.setCustomerProfile(jdCustomer);
                        boxOrderDetail.setBox(box);
                        boxOrderDetail.setSn("100");
                        boxOrderDetail.setOrderDetailStatus(BoxOrderDetailStatusEnum.valueOf(mapOrderState.name()));
                        boxOrderDetail.setPrice(detailPrice);
                        DateTime now = new DateTime();
                        DateTime dt2 = new DateTime(now.getYear(), now.getMonthOfYear(), now.getDayOfMonth(), 0, 0);
                        boxOrderDetail.setReserveDeliveryTime(dt2.toDate());
                        String boxOrderTitle = "";
                        if (osi.getItemInfoList() != null) {
                            Integer itemSize = osi.getItemInfoList().size();
                            if (itemSize == 1) {
                                boxOrderTitle = osi.getItemInfoList().get(0).getSkuName();
                            } else if (osi.getItemInfoList().size() > 1) {
                                boxOrderTitle = osi.getItemInfoList().get(0).getSkuName() + "等,共" + itemSize + "件商品";
                            }
                            boxOrderDetail.setQuantity(itemSize);
                        }
                        boxOrder.setDeliveryAddr(osi.getConsigneeInfo().getFullAddress());
                        boxOrder.setDeliveryCity(osi.getConsigneeInfo().getCity());
                        boxOrder.setDeliveryProvince(osi.getConsigneeInfo().getProvince());
                        boxOrder.setMobilePhone(osi.getConsigneeInfo().getMobile());
                        boxOrder.setCustomerMemo(osi.getOrderRemark());
                        boxOrder.setReceivePerson(osi.getConsigneeInfo().getFullname());
                        boxOrder.setMemo(osi.getVenderRemark());
                        ObjectMapper objectMapper = HibernateAwareObjectMapper.getInstance();
                        String rawDateString;
                        try {
                            rawDateString = objectMapper.writeValueAsString(osi);
                            boxOrder.setRawData(rawDateString);
                        } catch (JsonProcessingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        boxOrder.setTitle(boxOrderTitle);
                        boxOrder.setCustomerProfile(jdCustomer);
                        boxOrder.setRawData(osi.toString());
                        boxOrderDetail.setBoxOrder(boxOrder);
                        boxOrder.getBoxOrderDetails().add(boxOrderDetail);
                        result += "导入Jd订单：" + boxOrder.getOrderSeq() + ";";
                        // 发票信息
                        String invoiceInfo = osi.getInvoiceInfo();
                        if (invoiceInfo.contains(";")) {
                            for (String item : invoiceInfo.split(";")) {
                                String[] info = item.split(":");
                                if (info[0].equals("发票类型")) {
                                    boxOrder.setInvoiceType(info[1]);
                                } else if (info[0].equals("发票抬头")) {
                                    boxOrder.setInvoiceTitle(info[1]);
                                } else if (info[0].equals("发票内容")) {
                                    boxOrder.setInvoiceContent(info[1]);
                                }
                                boxOrder.setInvoiceCompany("北京美月淘电子商务有限公司");
                            }
                        }
                        boxOrderDao.save(boxOrder);
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
        if (commodityTitls.size() > 0) {
            PersonalMessage personalMessage = new PersonalMessage();
            String message = "";
            for (String msg : commodityTitls) {
                message += msg + ";<br> ";
            }
            result += "未找到京东商品： " + message + " 请在系统中维护商品的‘京东sku’或添加新商品";
            personalMessage.setContents("未找到京东商品：<br>  " + message + " 请在系统中维护商品的‘京东sku’或添加新商品");
            User user = userService.findByProperty("signinid", "admin");
            personalMessage.setPublishUser(user);
            personalMessage.setPublishTime(new Date());
            personalMessage.setTitle("京东订单导入后台，未找到相关商品");
            personalMessageDao.save(personalMessage);
            Role role = roleService.findByProperty("code", "ROLE_IYB_OPERATOR");// 运营部负责人（接收所有提醒）
            if (role != null) {
                personalMessageDao.save(personalMessage);
                List<UserR2Role> userR2Roles = userR2RoleDao.findByRole_Id(role.getId());
                for (UserR2Role item : userR2Roles) {
                    PersonalMessageItem personalMessageItem = new PersonalMessageItem();
                    personalMessageItem.setPersonalMessage(personalMessage);
                    personalMessageItem.setTargetUser(item.getUser());
                    personalMessageItemDao.save(personalMessageItem);
                }
            }
        }
        return result;
    }

    /**
     * 提交至跨境保税仓
     *
     * @param orderSid
     * @return
     */
    public String kjPost(String[] orderSid) {
        List<String> success = new ArrayList<String>();
        Map<String, String> fail = new HashMap<String, String>();
        for (String sid : orderSid) {
            BoxOrder boxOrder = boxOrderDao.findOne(Long.valueOf(sid));
            // 检查商品是否报备
            String cmsg = check(boxOrder);
            if (StringUtils.isNotBlank(cmsg)) {
                fail.put(boxOrder.getOrderSeq(), cmsg);
                continue;
            }
            // 是否关联身份证号
            KjUserValidateInfo vuser = kjUserValidateInfoService.findByProperty("mobilePhone", boxOrder.getMobilePhone());
            if (vuser == null) {
                fail.put(boxOrder.getOrderSeq(), "没有找到对应身份证号");
                continue;
            }
            KjOrderInfo kjOrderInfo = new KjOrderInfo(boxOrder, vuser.getIdNumber());
            String xml = kuajingMessageService.generateOrderInfoXml(kjOrderInfo);
            kjOrderInfo.setXmlStr(xml);
            // if(boxOrder.getOrderStatus() == BoxOrderStatusEnum.S20PYD){
            if (StringUtils.isNotBlank(boxOrder.getPayVoucher())) {
                // 有付款凭证 提交付款单
                KjPaymentInfo paymentInfo = new KjPaymentInfo(boxOrder);
                String pxml = kuajingMessageService.generatePaymentInfoXml(paymentInfo);
                kuajingMessageService.postMessage(pxml);
                paymentInfo.setXml(pxml);
                kjPaymentInfoService.save(paymentInfo);
            }
            kjOrderInfoService.save(kjOrderInfo);
            if (kuajingMessageService.postMessage(xml)) {
                success.add(boxOrder.getOrderSeq());
            } else {
                fail.put(boxOrder.getOrderSeq(), "return false");
            }
        }
        String msg = "";
        if (!success.isEmpty()) {
            msg += "提交成功:" + success.toString() + "\n";
        }
        if (!fail.isEmpty()) {
            msg += "提交失败:" + fail.toString();
        }
        return msg;
    }

    private String check(BoxOrder boxOrder) {
        String msg = "";
        for (BoxOrderDetail bod : boxOrder.getBoxOrderDetails()) {
            for (BoxOrderDetailCommodity bodc : bod.getBoxOrderDetailCommodities()) {
                Commodity c = bodc.getCommodity();
                if (c.getKjCommodityInfo() == null) {
                    msg += "商品：" + c.getSku() + "未报备 ";
                } else {
                    KjCommodityInfo info = c.getKjCommodityInfo();
                    if (info.getSkuStatusCode().equals(KjSkuStatusCodeEnum.KJS_30) || info.getSkuStatusCode().equals(KjSkuStatusCodeEnum.KJS_50)
                            || info.getSkuStatusCode().equals(KjSkuStatusCodeEnum.KJS_90)) {
                        // Pass
                    } else {
                        msg += "商品：" + c.getSku() + "未审核通过 ";
                    }
                }
            }
        }
        return msg;
    }
}
